<?php
namespace app\controllers;

use yii\web\Controller;
use Yii;
use yii\web\UnauthorizedHttpException;
use yii\web\Response;

class BaseController extends Controller
{
    public $enableCsrfValidation = false;
    public $ami = null;
    public $callcenter_db = null;
    public $cdr_db = null;
    public $asterisk_db = null;

    public function init()
    {
        $this->callcenter_db = Yii::$app->get('callcenter_db');
        $this->asterisk_db = Yii::$app->get('asterisk_db');
        $this->cdr_db = Yii::$app->get('cdr_db');
        $this->ami = new \AGI_AsteriskManager();
        //if ($this->ami->connect()==false){
            //return $this->asJson(['code'=>1,'msg'=>'ami未连接']);
        //}
    }

    public function reload()
    {
        if (Yii::$app->params['auto_reload_asterisk']){
            if(is_file("/usr/share/issabel/privileged/applychanges")) {
                $sComando = '/usr/bin/issabel-helper applychanges';
                $output = $ret = NULL;
                exec($sComando, $output, $ret);
            }
        }
    }

    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)){
            return false;
        }
        $controller = $action->controller->id;
        $action = $action->id;
        //超级管理员ID为1
        if (Yii::$app->user->identity->getId()==Yii::$app->params['super_user_id']){
            return true;
        }
        if (Yii::$app->user->can($controller.'/*')){
            return true;
        }
        if (Yii::$app->user->can($controller.'/'.$action)){
            return true;
        }
        if (Yii::$app->request->isAjax){
            Yii::$app->response->format = Response::FORMAT_JSON;
            Yii::$app->response->data = ['code' => 1, 'msg' => '未授权访问'];
            return false;
        }
        throw new UnauthorizedHttpException('未授权访问');
        return true;
    }

}